//退出登录
function logout() {
    $.ajax({
        url: '/csfy/dologout.do',
        method: 'POST',
        success: function (res) {
            if (JSON.parse(res).code == 200) {
                window.location.href = "/csfy/index.do"
            }
        }
    })
}

//获取当前登录用户信息
$(document).ready(function () {
    $.ajax({
        method: 'POST',
        url: '/csfy/intf.do',
        data: { method: 'getLoginUserInfo' },
        success: res => {
        if (res.code == 10086) {
         //window.location.href = "/csfy/index.do"
        alert("请重新登录！");
        } else {
        if (res.code == 200) {
            $(".username").html(res.rows.userName);
        }
      }
   }
  });
})


    //用户类型
    function getUserType(type) {
        type = parseInt(type);
        if (isNaN(type)) {
            return ' ';
        }
        if (type == 0) {
            return 'UAMS管理员';
        } else if (type == 1) {
            return '华大员工';
        }else if(type == 2){
            return '外包账号';
        }else if(type == 3){
            return '外部用户';
        }
    }

    //员工状态
    function getUserStatus(type) {
        type = parseInt(type);
        if (isNaN(type)) {
            return '';
        }
        if (type == 1) {
            return '在职';
        } else if (type == 0) {
            return '离职';
        }
    }

    //用户性别
    function getSex(type){
        type = parseInt(type);
        if (isNaN(type)) {
            return '';
        }
        if(type == 0){
            return "未知";
        }
        if (type == 1) {
            return '女';
        } else if (type == 2) {
            return '男';
        }
    }

    //TODO 获取详情信息
   /* $.ajax({
        url: '/csfy/user/findAllUamsUser.do?userId='+id,
        method: 'POST',
        //data: { method: 'findAllUamsUser.do', userId: id },
        success: function (res) {
            res = JSON.parse(res);
            if (res.code == 200 && res.rows) {
                $("#user-name").html(res.rows[0].userName);
                $("#user-mobile").html(res.rows[0].userMobile);
                $("#real-name").html(res.rows[0].realName);
                $("#user-sex").html(getSex(res.rows[0].userSex));
                $("#user-address").html(res.rows[0].userAddr);
                $("#user-email").html(res.rows[0].userEmail);
                $("#qq-num").html(res.rows[0].userQQ);
                $("#user-type").html(getUserType(res.rows[0].userType));
                $("#user-status").html(getUserStatus(res.rows[0].userStatus));

                //获取权限信息
                var firstMenu = res.rows[0].menuCodeFirst;
                var secondMenu = res.rows[0].menuCodeSecond;

                var fMenuLsit=[];
                var sMenuList=[];
                if(firstMenu != null && firstMenu !="" ){
                    firstMenu =firstMenu.substr(0,firstMenu.length - 1);
                    fMenuLsit = firstMenu.split(",");
                }

                if(secondMenu !=null && secondMenu !=""){
                    secondMenu =secondMenu.substr(0,secondMenu.length - 1);
                    sMenuList = secondMenu.split(",");
                }

                for(var i in fMenuLsit) {
                    $("#fMenu-" + fMenuLsit[i]).attr("checked", true);
                }
                if (sMenuList != "" && sMenuList != null) {
                    for (var j in sMenuList) {
                        $("#sub-" + sMenuList[j]).attr("checked", true);
                    }
                }

            } else {
                alert('获取用户权限信息失败，请稍后重试');
                window.location.href = "/csfy/static/manage-sys/power-manage.html"
            }
        },
        error: function (msg) {
            console.log("错误信息："+msg);
            window.location.href = "/csfy/static/manage-sys/power-manage.html"
        }
    })*/


//验证所填信息
function checkData(){
   var userName = $("#user-name").val();
   var userMobile = $("#user-mobile").val();
   var userPwd = $("#user-pwd").val();
   var userRePwd = $("#user-repwd").val();
   var realName = $("#real-name").val();
   var userSex = $("#user-sex").val();
   var userAddr =  $("#user-address").val();
   var userEmail = $("#user-email").val();
   var userQQ = $("#qq-num").val();
   var userType = $("#user-type").val();
   var userStatus = $("#user-status").val();
   
   $("div.base input[validate='required']").each(function () {
       if($(this).val() == "" || $(this).val() == null){
           alert("请填写带星号(*)的必填项！");
           return false;
       }
   });

   //验证用户名
    if(!/^[a-zA-Z][a-zA-Z0-9]{2,15}$/i.test(userName)){
        alert("用户名不合法（字母开头，允许3-16字节，允许字母数字）");
        return false;
    }

    //验证手机号码
    if(userMobile !="" && userMobile !=null && !/^(13|15|18|17)\d{9}$/i.test(userMobile)){
        alert("手机号码格式不正确");
        return false;
    }

    //验证密码
    if(userPwd != userRePwd){
        alert("两次输入的密码不一样！");
        return false;
    }

    if(userPwd.length < 6 || userPwd.length > 16){
        $(".tishi").text("密码长度为6~16位！");
    }else {
        $(".tishi").text("");
    }

    //验证邮箱
    if(userEmail != "" && userEmail != null){
        var reg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/;
        if(!reg.test(userEmail)){
            alert("邮箱格式不正确！");
            return false;
        }
    }

    //验证QQ号码
    if(userQQ != "" && userQQ != null){
        if(!/^[1-9]\d{4,9}$/i.test(userQQ)){
            alert("QQ号码格式不正确！");
            return false;
        }
    }
     return true;
}

function save(){
     //验证所有所填表单信息
    if(checkData()){
        var userName = $("#user-name").val();
        var userMobile = $("#user-mobile").val();
        var userPwd = $("#user-pwd").val();
        var realName = $("#real-name").val();
        var userSex = $("#user-sex option:selected").val();
        var userAddr =  $("#user-address").val();
        var userEmail = $("#user-email").val();
        var userQQ = $("#qq-num").val();
        var userType = $("#user-type option:selected").val();
        var userStatus = $("#user-status option:selected").val();

        //保存权限信息
        var powerList=[];

        $("#power-list .icon-wrapper input[type='checkbox']:checked").each(function (){
            powerList.push($(this).val());
        });

        /*console.log(
            "用户提交信息：用户名："+userName+"，电话号码："+userMobile+"，密码："+userPwd+
            "，真实姓名："+realName+"，性别："+userSex+"，地址："+userAddr+"，邮箱："+userEmail+
            "，QQ："+userQQ +"，用户类型："+userType+"，员工状态："+userStatus+"，权限信息："+powerList
        );*/

        //TODO 提交保存权限信息
        $.ajax({
            url: '/csfy/user/CreateUserWithMenu.do' ,
            type: 'POST',
            dataType :'json',
            data: { userName: userName ,userPwd: userPwd,realName: realName,userSex: userSex,userEmail:userEmail,
                userMobile:userMobile ,userQQ:userQQ ,userAddr: userAddr ,userStatus: userStatus ,userType:userType ,menus:powerList},
            success: function (res) {
                //console.log(res);
                if (res.code == 200 && res.rows) {
                    alert("用户信息添加成功！");
                   // window.location.href = "/csfy/static/manage-sys/power-manage.html";
                    callParent("权限分配","/csfy/static/manage-sys/power-manage.html");
                    //关闭当前tab
                    closeCurrentTab("添加用户权限");
                }
            },
            error: function (msg) {
                alert('添加用户信息失败，请稍后重试');
                callParent("权限分配","/csfy/static/manage-sys/power-manage.html");
                //关闭当前tab
                closeCurrentTab("添加用户权限");
                //console.log("添加用户信息失败，"+JSON.parse(msg));
                //window.location.href = "/csfy/static/manage-sys/power-manage.html"
            }
        })

    }
}

//添加tab
function callParent(title,url) {
    // var menuName=parent.$('#tt').tabs('getSelected').panel('options').title;
    //如果存在，直接刷新页面
    if (parent.$('#tt').tabs('exists', title)) {
        parent.$('#tt').tabs('close', title);
        window.parent.addTab(title, url);
    } else {
        window.parent.addTab(title, url);
    }
}

//关闭当前tab
function closeCurrentTab(title) {
    parent.$("#tt").tabs('close',title);
}